<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="utf-8" />
    <title>导入（续费/修改账密）</title>
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
    <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />
    <link rel="stylesheet" href="/app/admin/admin/css/pages/orderdetail.css" />
    <style rel="stylesheet" type="text/css">
      .match-btn {
        text-align: center;
      }
      .layui-btn-container button {
        margin-right: 10px;
      }
      .layui-form[lay-filter='onlyexpire-form'] {
        margin-top: 0;
      }
      .mb-8 {
        margin-bottom: 8px;
      }
      .import-icons i {
        font-size: 1.4rem;
      }
    </style>
  </head>
  <body class="pear-container">
  <!-- 顶部查询表单 -->
  <div class="layui-card">
    <div class="layui-card-body">
      <form class="layui-form top-search-from">
        <input type="hidden" name="user_id" value="<?=$user_id?>" class="layui-input"/>

        <?php if ($user_id > 0): ?>
        <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
          <ul class="layui-tab-title" id="typeData"></ul>
        </div>
        <div class="layui-tab-content"></div>
        <input type="hidden" name="line_id" value="" id="line_id">
        <?php else: ?>
        <?php endif; ?>
      </form>
    </div>
  </div>

    <!-- 导入操作/续费/到期 -->
    <div class="layui-card">
      <div class="layui-card-body">
        <div>
          <strong>请将节点信息放入下面</strong>
        </div>
        <div class="flex align-center justify-between mb-8">
          <div>
            <form class="layui-form" lay-filter="onlyexpire-form">
              <input
                type="checkbox"
                name="onlyexpire"
                title="只显示到期数据"
                lay-skin="primary"
              />
            </form>
          </div>
          <div class="import-icons">
            <!-- <button class="pear-btn pear-btn-primary">
              <i class="layui-icon layui-icon-download-circle"></i>
            </button>
            <button class="pear-btn pear-btn-primary">
              <i class="layui-icon layui-icon-print"></i>
            </button> -->
          </div>
        </div>
        <div class="layui-row layui-col-space30">
          <div class="layui-col-md6">
            <textarea
              name="ips"
              placeholder="ip|port|user|pass|time
ip:port user pass time
ip port user pass time"
              class="layui-textarea"
              rows="6"
            ></textarea>
          </div>
          <div class="layui-col-md6">
            <textarea
              name="faildata"
              placeholder="匹配失败的数据"
              class="layui-textarea"
              rows="6"
            ></textarea>
          </div>
        </div>

        <div class="match-btn">
          <button class="pear-btn pear-btn-primary">匹配</button>
        </div>

        <div class="table-container" style="display: none">
          <!-- 匹配导入后结果 -->
          <p>
            <strong>本次导入有效代理 <span id="match-count">0</span> 条</strong>
          </p>

          <hr />

          <!-- controller. -->
          <div class="layui-btn-container">
            <button plain class="pear-btn pear-btn-primary pear-btn-md" lay-event="group">
              分组
            </button>
            <button plain class="pear-btn pear-btn-primary pear-btn-md mr8" lay-event="remark">
              备注
            </button>
            <button
              plain
              type="button"
              class="pear-btn pear-btn-primary pear-btn-md"
              lay-event="renew"
            >
              续费
            </button>
            <button
              plain
              type="button"
              class="pear-btn pear-btn-primary pear-btn-md"
              lay-event="transfer-ownership"
            >
              过户
            </button>
            <button
              plain
              type="button"
              class="pear-btn pear-btn-primary pear-btn-md"
              lay-event="average-time"
            >
              平均时间
            </button>
            <button
              plain
              type="button"
              class="pear-btn pear-btn-primary pear-btn-md"
              lay-event="change-password"
              style="margin-right: 20px"
            >
              改密
            </button>
            <button
              plain
              type="button"
              class="pear-btn pear-btn-primary pear-btn-md"
              lay-event="changeip-1"
            >
              同地区调换
            </button>
            <button
              plain
              type="button"
              class="pear-btn pear-btn-primary pear-btn-md"
              lay-event="changeip-2"
            >
              随机地区调换
            </button>
            <button
              plain
              type="button"
              class="pear-btn pear-btn-primary pear-btn-md"
              lay-event="changeip-3"
            >
              自选地区调换
            </button>

            <?php if ($config['order_node_renew_auto']): ?>
            <button plain class="pear-btn pear-btn-primary pear-btn-md" lay-event="renewAutoOpen">自动续费开启</button>
            <?php else: ?>
            <?php endif; ?>
            <button plain class="pear-btn pear-btn-primary pear-btn-md" lay-event="renewAutoOff">自动续费关闭</button>
            <button plain class="pear-btn pear-btn-primary pear-btn-md" lay-event="bind">解绑</button>

          </div>
          <!-- TableList. -->
          <table id="import-table" lay-filter="import-table"></table>
        </div>
      </div>
    </div>

    <!-- 续费 WRAPPER_BOX -->
    <div id="renew-wrapper" style="display: none">
      <div id="renew-table"></div>
      <div class="renew-footer flex align-center justify-between">
        <div class="tips-left">
          <!-- 已选续费数量1条，应付1.5积分， 成功0条，失败0条 -->
        </div>
        <div class="tips-right flex align-center">
          <div class="tips-right__1 flex align-center mr8">
            <span>续费时间：</span>
            <div id="select-time" name="select-time"></div>
          </div>
          <div class="tips-right__2">
            <button class="pear-btn pear-btn-primary" id="confirm-renew">
              确认续费
            </button>
            <button class="pear-btn" id="cancel-renew">取消</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 过户 WRAPPER_BOX -->
    <div id="transfer-ownership-wrapper" style="display: none">
      <div id="transfer-os-table" lay-filter="transfer-os-table"></div>
      <div class="fransfer-os-footer flex align-center justify-between">
        <div class="placeholder"></div>
        <div class="tips-right flex align-center">
          <div class="tips-right__1 flex align-center mr8">
            <input
              type="text"
              placeholder="请输入用户名称进行搜索"
              class="layui-input transfer-input"
            />
          </div>
          <div class="tips-right__2">
            <button class="pear-btn pear-btn-primary" id="search-users">
              搜索用户
            </button>
            <button class="pear-btn" id="search-users-cancel">取消</button>
          </div>
        </div>
      </div>
    </div>
    <!-- 过户 - 操作 -->
    <script type="text/html" id="transfer-os-bar">
      <a lay-event="transfer-ownership" class="mr-1"
        ><i class="pear-icon  pear-icon-release"></i>过户</a
      >
    </script>

    <!-- 平均时间 -->
    <div id="average-time-wrapper" style="display: none">
      <div id="average-timebox"></div>
      <div class="bn-times">
        <input
          type="text"
          name="expire_time_average_time"
          id="expire_time_average_time"
          autocomplete="off"
          class="layui-input"
          placeholder="请输入平均时间"
        />
        <ul></ul>
      </div>
    </div>

    <!-- 修改密码 -->
    <div id="change-password-wrapper" style="display: none">
      <div style="padding: 10px">
        <input
          type="text"
          id="change-password-input"
          class="layui-input"
          placeholder="请输入新密码"
          style="max-width: 290px"
        />
      </div>
      <div id="change-password"></div>
    </div>

    <!-- 同地区调换 -->
    <div id="change-same-area-wrapper" style="display: none">
      <div
        class="layui-tab layui-tab-brief"
        lay-filter="change-same-area-tab"
        style="display: none"
      >
        <ul class="layui-tab-title"></ul>
        <!-- <div class="layui-tab-content" style="height: 1px">
          <div class="layui-tab-item layui-show"></div>
          <div class="layui-tab-item"></div>
          <div class="layui-tab-item"></div>
          <div class="layui-tab-item"></div>
          <div class="layui-tab-item"></div>
        </div> -->
      </div>
      <div id="change-same-area-table"></div>
      <form
        onsubmit="return false;"
        class="layui-form"
        lay-filter="change-same-area-form"
      >
        <div class="layui-form-item">
          <label class="layui-form-label">自定义账号</label>
          <div class="layui-input-block" id="custom-accounts"></div>
        </div>
        <div class="layui-form-item">
          <div class="layui-inline">
            <label class="layui-form-label">账号</label>
            <div class="layui-input-block">
              <input
                type="text"
                name="account"
                lay-verify="required"
                placeholder="请输入账号"
                autocomplete="off"
                class="layui-input"
              />
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-inline" style="max-width: 300px">
              <input
                type="text"
                name="pass"
                autocomplete="off"
                class="layui-input"
                placeholder="请输入密码"
              />
            </div>
          </div>
        </div>
        <!-- NOTE: 指定地区调换才展示自动输入 -->
        <div class="layui-form-item" style="display: none" type="appoint">
          <label class="layui-form-label">自动输入</label>
          <div class="layui-input-block">
            <div class="layui-inline">
              <input
                class="layui-input number-input-value"
                type="number"
                style="max-width: 180px"
                min="0"
                placeholder="节点数量"
                readonly
              />
            </div>
            <div class="layui-inline">
              <button
                class="pear-btn pear-btn-sm pear-btn-primary"
                id="autoinput-confirm"
              >
                <i class="layui-icon layui-icon-ok"></i>
                确认
              </button>
              <button class="pear-btn pear-btn-sm" id="autoinput-cancel">
                <i class="layui-icon layui-icon-close"></i>
                清空
              </button>
            </div>
            <div class="layui-inline">
              <!-- 提交信息 -->
              <div
                class="layui-input-inline layui-input-inline--autow flex align-center bn-submit-box"
              >
                <div>
                  剩余调换次数
                  <span class="point-score text-color-blue" id="max-count"
                    >0</span
                  >
                </div>
                <div>
                  <!-- <i class="layui-icon layui-icon-website text-color-blue"></i> -->
                  待选
                  <span class="point-score text-color-blue" id="wait-count"
                    >0</span
                  >
                </div>
                <div>
                  <i class="layui-icon layui-icon-senior text-color-blue"></i
                  >已选地区<span
                    class="point-score text-color-blue"
                    id="sel-area-count"
                    >0</span
                  >台
                </div>
                <div>
                  <i class="layui-icon layui-icon-website text-color-blue"></i
                  >已选总IP<span
                    class="point-score text-color-blue"
                    id="sel-ip-count"
                    >0</span
                  >台
                </div>
                <!-- <div>
                  <i class="layui-icon layui-icon-cellphone text-color-blue"></i
                  >消耗金币<span
                    class="point-score text-color-blue"
                    id="sel-score-count"
                    >0</span
                  >
                </div> -->
              </div>
            </div>
          </div>
        </div>
        <!-- <div class="layui-form-item">
          <label class="layui-form-label">自选端口</label>
          <div class="layui-input-block">
            <div id="custom-port" name="custom-port"></div>
          </div>
        </div> -->
      </form>
    </div>

    <!-- 订单确认 -->
    <div class="order-confirm-wrapper" style="display: none">
      <table id="confirm-order-table" lay-filter="confirm-order-table"></table>
    </div>

    <script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
    <script src="/app/admin/component/pear/pear.js"></script>
    <script src="/app/admin/admin/js/permission.js"></script>
    <script src="/app/admin/admin/js/common.js"></script>
    <script src="/app/admin/admin/js/import.js"></script>
    <script src="/app/admin/admin/js/apis.js"></script>

    <script type="text/javascript">
      let defaultUserId = '<?=$user_id?>';
      let defaultLineId = '<?=$line_id?>';

      // 相关常量
      const PRIMARY_KEY = 'id'
      const SELECT_API = '/app/admin/v1-game/select'
      const IMPORT_MATCHING = '/app/admin/v1-api/importMatchingData' // 导入匹配

      const GROUP_API = '/app/admin/v1-order-node/group'
      const REMARK_API = '/app/admin/v1-order-node/remark'
      const ORDERDETAIL_GAME_URL = '/app/admin/v1-node/orderdetail_game'
      const RENEW_AUTO_OPEN_API = '/app/admin/v1-api/renewAutoOpen';
      const BIND_API = '/app/admin/v1-api/bind'
      let configText = "<?=$config['text']?>";

      let apiResults = {}

      function getLineId() {
        const params = new URL(location.href).searchParams
        return params.get('line_id')
      }
      window.refreshTable = () => {
        console.log('11111','111111111111111');
        // 刷新页面.
        // 重新执行匹配操作
        layui.$('.match-btn button').click()
      }

      // 表格渲染
      layui.use(
        ['table', 'form', 'common', 'popup', 'util', 'xmSelect','notice'],
        function () {
          let table = layui.table
          let form = layui.form
          let $ = layui.$
          let common = layui.common
          let util = layui.util
          let layer = layui.layer

          // defaultLineId = APILIST.getLineId() // 获取默认 LineId

          // 获取表格中下拉或树形组件数据
          let apis = []
          apis.push(['game_id', '/app/admin/v1-game/select2?format=tree'])
          apis.push(['duration', '/app/admin/dict/getNew/get_duration_type_list'])
          apis.push(['region_id', '/app/admin/v1-region/select2?format=tree'])
          apis.push(["renew_status", "/app/admin/dict/getNew/get_open_off_list"]);
          let apiResults = {}
          apiResults['duration'] = []
          apiResults['game_id'] = []
          apiResults['region_id'] = []
          apiResults["renew_status"] = [];
          let count = apis.length
          layui.each(apis, function (k, item) {
            let [field, url] = item
            $.ajax({
              url: url,
              dateType: 'json',
              success: function (res) {
                if (res.code) {
                  return layui.popup.failure(res.msg)
                }
                function travel(items) {
                  for (let k in items) {
                    let item = items[k]
                    apiResults[field][item.value] = item.name
                    if (item.children) {
                      travel(item.children)
                    }
                  }
                }
                travel(res.data)
              },
              complete: function () {
                if (--count === 0) {
                  // render()
                }
              },
            })
          })

          // 导入表头
          const importsCols = [
            {
              type: 'checkbox',
              align: 'left',
              width: 50,
            },
            {
              title: '主键',
              align: 'left',
              field: 'id',
              sort: true,
              width: 110,
            },
            {
              title: "自动续费",align: "left",
              field: "renew_status",
              templet: function (d) {
                let field = "renew_status";
                if (typeof d[field] == "undefined") return "";
                let items = [];
                layui.each((d[field] + "").split(","), function (k , v) {
                  items.push(apiResults[field][v] || v);
                });
                return util.escape(items.join(","));
              },
              width: 100,
            },
            {
              title: '订单号',
              align: 'left',
              field: 'order_no',
              width: 220,
            },
            {
              title: '项目',
              align: 'left',
              field: 'game',
              templet: function (d) {
                return d.game ? d.game.name : ''
              },
              width: 200,
            },
            {
              title: '地区',
              align: 'left',
              field: 'region',
              templet: function (d) {
                return d.region ? d.region.name : ''
              },
              width: 200,
            },
            {
              title: 'ip',
              align: 'left',
              field: 'ip',
              width: 150,
            },
            {
              title: '端口',
              align: 'left',
              field: 'port',
              width: 100,
            },
            {
              title: '用户名',
              align: 'left',
              field: 'account',
              width: 120,
            },
            {
              title: '密码',
              align: 'left',
              field: 'pass',
              width: 120,
            },
            {
              title: '购买时间',
              align: 'left',
              field: 'created_at',
              width: 160,
            },
            {
              title: '到期时间',
              align: 'left',
              field: 'expire_time',
              width: 160,
            },
            {
              title: '分组',
              align: 'left',
              field: 'group',
              width: 100,
            },
            {
              title: '备注',
              align: 'left',
              field: 'remark',
              width: 160,
            },
            {
              title: '时长类型',
              align: 'left',
              field: 'duration',
              templet: function (d) {
                let field = 'duration'
                if (typeof d[field] == 'undefined') return ''
                let items = []
                layui.each((d[field] + '').split(','), function (k, v) {
                  items.push(apiResults[field][v] || v)
                })
                return util.escape(items.join(','))
              },
              width: 110,
            },
            {
              title: '金币',
              align: 'left',
              field: 'amount',
              width: 100,
            },
          ]

          // 渲染表格
          const tableInstance = table.render({
            elem: '#import-table',
            //   url: SELECT_API,
            page: false,
            cols: [importsCols],
            skin: 'line',
            autoSort: false,
            data: [],
          })

          const $onlyExpireElement = $('input[name="onlyexpire"]')
          const $ipsElement = $('textarea[name="ips"]')
          const $faildataElement = $('textarea[name="faildata"]')
          const $tableBox = $('.table-container')

          // 匹配操作
          $('.match-btn button').on('click', function () {
            const ipsVal = $ipsElement.val()
            if (!ipsVal) return layer.msg('导入数据不能为空')
            const isExpire = $onlyExpireElement.is(':checked')
            postMatchingIps(
              {
                user_id: defaultUserId,
                line_id: defaultLineId,
                is_expire: Number(isExpire),
                content: ipsVal,
              },
              (data) => {
                if (data) {
                  layer.msg('导入成功')
                  const { errorData = [], successData = [] } = data

                  let errTips = errorData.join('\n')
                  $faildataElement.val(errTips)
                  $tableBox.show()
                  $('#match-count').text(successData.length)

                  table.reload('import-table', {
                    data: successData,
                  })
                }
              }
            )
          })

          function postMatchingIps(data, callback) {
            layui.$.ajax({
              url: IMPORT_MATCHING,
              type: 'POST',
              dataType: 'json',
              data,
              success(res) {
                if (res.code) {
                  layui.layer.clearAll('loading')
                  return global.layer.msg(res.msg)
                }
                callback && callback(res.data)
              },
            })
          }


          $('div.layui-btn-container > button').on('click', function () {
            const that = $(this)
            const $btn = $(that.context)
            const event = $btn.attr('lay-event')
            const data = layui.table.checkStatus('import-table').data
            if (!data || !data.length) return layui.popup.warning('未选中数据')

            switch (event) {
                    // case 'export':
                    //   exportTxt(obj)
                    //   break
                    // case 'copy':
                    //   __copy_txt__(obj)
                    //   break
              case 'group':
                group(data)
                break
              case 'remark':
                remark(data)
                break
              case 'renew':
                __renew_operate__(data)
                break
              case 'transfer-ownership':
                __transfer_ownership__(data)
                break
              case 'average-time':
                __average_time__(data)
                break
              case 'change-password':
                __change_password__(data)
                break
              case 'changeip-1':
                executeAction({ id: 1 }, data)
                break
              case 'changeip-2':
                executeAction({ id: 2 }, data)
                break
              case 'changeip-3':
                executeAction({ id: 3 }, data)
                break
              case 'renewAutoOpen':
                renewAutoOpen(data,1)
                break
              case 'renewAutoOff':
                renewAutoOpen(data,0)
                break
              case 'bind':
                bind(data)
                break
            }
          })

          /*-------按钮操作 start----------*/

          // 分组
          let group = function (data) {
            if (!data || !data.length){
              return layui.popup.warning('未选中数据')
            }
            const order_node_ids = data.map((item) => item.id)
            doGroup(order_node_ids)
          }

          // 执行分组
          let doGroup = function (ids) {
            layer.prompt(
                    { title: '请输入分组数字' },
                    function (value1, index, elem) {
                      let group = value1
                      if (group === '') {
                        return layui.popup.failure('请输入分组数字')
                      }

                      layer.close(index)
                      let loading = layer.load()
                      $.ajax({
                        url: GROUP_API,
                        data: { id: ids, group: group },
                        dataType: 'json',
                        type: 'post',
                        success: function (res) {
                          layer.close(loading)
                          if (res.code) {
                            return layui.popup.failure(res.msg)
                          }
                          window.refreshTable()
                          return layui.popup.success(res.msg)
                        },
                        error: function () {
                          layer.close(loading)
                          return layui.popup.failure('网络错误')
                        },
                      })
                    }
            )
          }

          // 备注
          let remark = function (data) {
            if (!data || !data.length){
              return layui.popup.warning('未选中数据')
            }
            const order_node_ids = data.map((item) => item.id)
            doRemark(order_node_ids)
          }

          // 执行备注
          let doRemark = function (ids) {
            layer.prompt(
                    { title: '请输入备注' },
                    function (value1, index, elem) {
                      let remark = value1
                      if (remark === '') {
                        return layui.popup.failure('请输入备注')
                      }

                      layer.close(index)
                      let loading = layer.load()
                      $.ajax({
                        url: REMARK_API,
                        data: { id: ids, remark: remark },
                        dataType: 'json',
                        type: 'post',
                        success: function (res) {
                          layer.close(loading)
                          if (res.code) {
                            return layui.popup.failure(res.msg)
                          }
                          window.refreshTable()
                          return layui.popup.success(res.msg)
                        },
                        error: function () {
                          layer.close(loading)
                          return layui.popup.failure('网络错误')
                        },
                      })
                    }
            )
          }

          // 续费操作
          let __renew_operate__ = function (data) {
            if (!data || !data.length) return layui.popup.warning('未选中数据')

            let selectTime = null

            //
            const renderPirce = (
              item,
              ops = {
                success: 0,
                error: 0,
              }
            ) => {
              const len = data.length
              const money = parseFloat(item.money)
              const totalMoney = money * len
              // $('#renew-wrapper .tips-left').html(
              //   `已选续费数量<span>${len}</span>条，应付<span>${totalMoney}</span>积分， 成功<span>${ops.success}</span>条，失败<span>${ops.error}</span>条`
              // )
              $('#renew-wrapper .tips-left').html(`已选续费数量<span>${len}</span>条，应付<span>${totalMoney}</span>积分`)
            }

            const renderRenewTable = function () {
              layui.table.render({
                elem: '#renew-table',
                height: 'full',
                data,
                skin: 'line',
                toolbar: false,
                cols: [
                  [
                    { field: 'ip', title: 'IP' },
                    { field: 'account', title: '用户名' },
                    { field: 'expire_time', title: '到期时间' },
                    {
                      field: 'status',
                      title: '状态',
                      templet: function (d) {
                        return '未续费'
                        // return d.status == 1 ? '已续费' : '未续费'
                      },
                    },
                  ],
                ],
                done: function () {
                  // 先解绑之前的事件，防止重复绑定
                  $('#confirm-renew').off('click');
                  $('#cancel-renew').off('click');

                  // 注册确定与取消事件
                  $('#confirm-renew').on('click', function () {
                    // NOTE: 确定续费接口
                    layui.layer.load()
                    APILIST.postRenewDuration(
                      {
                        user_id: defaultUserId, // UserId
                        line_id: defaultLineId, // 线路ID
                        duration: selectTime.duration, // duration 时长类型
                        ids: data.map((item) => item.id), // 订单节点ID
                      },
                      function (res) {
                        layui.layer.closeAll('loading')
                        layui.notice.info(res.msg)
                        // TODO: 此处应该由后端返回 (成功&失败数量)
                        renderPirce(selectTime, {
                          success: data.length,
                          error: 0,
                        })
                        setTimeout(() => {
                          layer.closeAll()
                          window.refreshTable()
                        }, 1100)
                      }
                    )
                  })

                  // cancel window.
                  $('#cancel-renew').on('click', function () {
                    layer.closeAll()
                  })
                },
              })

              APILIST.getNodeRenewDurationList(defaultLineId, function (list) {
                const thirdData = list[2]

                const getDefault = (item) => {
                  if (!item) return ''
                  return [`${item.duration}|${item.money}`]
                }

                renderPirce(thirdData)

                selectTime = thirdData

                layui.xmSelect.render({
                  el: '#select-time',
                  name: 'select-time',
                  initValue: getDefault(thirdData),
                  filterable: false,
                  direction: 'up',
                  data: list.map((item) => ({
                    ...item,
                    name: item.name,
                    value: `${item.duration}|${item.money}`,
                  })),
                  model: { icon: 'hidden', label: { type: 'text' } },
                  clickClose: true,
                  radio: true,
                  on: function (selData) {
                    if (!selData) return
                    const sel = selData.arr[0]
                    renderPirce(sel)
                    selectTime = sel
                  },
                })
              })
            }

            layer.open({
              type: 1,
              title: '续费',
              shade: 0.1,
              maxmin: false,
              area: [common.isModile() ? '100%' : '60%', common.isModile() ? '100%' : '95%',],
              content: $('#renew-wrapper'),
              success: function () {
                renderRenewTable()
              },
            })
          }

          //   过户操作
          let __transfer_ownership__ = function (data) {
            if (!data || !data.length) return layui.popup.warning('未选中数据')
            const ipIds = data.map((item) => item.id)
            let OtherData = {
              username: '',
            }

            const renderTransferTable = function () {
              layui.table.render({
                elem: '#transfer-os-table',
                // url: APILIST.getInvitationUserListURL,
                url: '',
                method: 'post',
                where: OtherData,
                data: [],
                // 此处需要把要过户的IP列表放到data数据中 方便取用
                parseData: function (res) {
                  return {
                    code: res.code, //解析接口状态
                    msg: res.message, //解析提示文本
                    // count: res.total, //解析数据长度
                    data: res.data.map((item) => {
                      // data: [
                      //   {
                      //     account: 'text data.',
                      //   },
                      // ].map((item) => {
                      return {
                        ...item,
                        _ips: ipIds,
                      }
                    }),
                  }
                },
                height: 'full',
                skin: 'line',
                toolbar: false,
                cols: [
                  [
                    { field: 'account', title: '用户名' },
                    {
                      field: 'status',
                      title: '认证状态',
                      templet: function (d) {
                        return d.status == 1 ? '已认证' : '未认证'
                      },
                    },
                    {
                      title: '操作',
                      toolbar: '#transfer-os-bar',
                      align: 'center',
                      fixed: 'right',
                      width: 120,
                    },
                  ],
                ],
                done: function () {
                  // 查询接口
                  $('#search-users').on('click', function () {
                    const username = $('input.transfer-input').val()
                    table.reload('transfer-os-table', {
                      url: APILIST.getInvitationUserListURL,
                      where: {
                        username,
                      },
                      // done(){} // 可以清空数据
                    })
                  })

                  //   cancel window.
                  $('#search-users-cancel').on('click', function () {
                    layer.closeAll()
                    $('input.transfer-input').val('')
                  })
                },
              })
            }

            layer.open({
              type: 1,
              title: '过户',
              shade: 0.1,
              maxmin: false,
              area: [common.isModile() ? '100%' : '60%', common.isModile() ? '100%' : '95%',],
              content: $('#transfer-ownership-wrapper'),
              success: function () {
                renderTransferTable()
              },
              cancel(index) {
                layer.close(index)
                $('input.transfer-input').val('')
              },
            })
          }

          // NOTE: 过户操作
          table.on('tool(transfer-os-table)', function (obj) {
            if (obj.event === 'transfer-ownership') {
              layer.load()
              APILIST.setTransferUser(
                {
                  line_id: defaultLineId,
                  to_user_id: obj.data.id,
                  ids: obj.data._ips,
                  user_id: defaultUserId, // UserId
                },
                (res) => {
                  layer.closeAll('loading')
                  layui.notice.info(res.msg)
                  window.refreshTable()
                  window.setTimeout(() => {
                    layui.layer.closeAll()
                  }, 1000)
                }
              )
            }
          })

          // 平均时间
          let __average_time__ = function (data) {
            if (!data || !data.length) return layui.popup.warning('未选中数据')
            const maxTime = Math.max(
              ...data.map((item) => new Date(item.expire_time).getTime())
            )

            let expireTime = ''
            let minTime = '-1'
            let currentTime = ''

            if (maxTime) {
              let date = new Date(maxTime)
              expireTime = `${date.getFullYear()}-${
                date.getMonth() + 1
              }-${date.getDate()}`
              // ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}
            }

            // 获取用户信息
            // APILIST.getBaseInfo((user_extend) => {
            //   const formatList = setIndexInfo(user_extend, defaultLineId)
            //   const cur = formatList.find((item) => item.default && item.show)
            //   if (cur) currentTime = cur.type
            //   renderBNTimes(formatList)
            //   // 时长操作逻辑
            // })

            // bn-times
            if (!$('.bn-times ul li').length) {
              APILIST.getAverageTimeList((data) => {
                // console.log('%c ??? >>>', 'background: blue; color: #fff', data)
                // {min: 1, max: 10, amount: '5'}
                const fragments = new DocumentFragment()
                $.each(data, (index, { min, max, amount }) => {
                  fragments.append(
                    $(`<li>${min}~${max}天:${amount}金币</li>`)[0]
                  )
                })

                $('.bn-times ul').append(fragments)
              })
            }

            layui.laydate.render({
              elem: '#expire_time_average_time',
              type: 'date',
              min: expireTime, // 2012-1-1
              // max: '', // max: '2017-12-31'
              done(value, date, endDate) {
                currentTime = value
                // console.log(value) //得到日期生成的值，如：2017-08-18
                // console.log(date) //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                // console.log(endDate) //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
              },
            })

            // $('.bn-times').on(
            //   'click',
            //   'button:not([data-type="btn"])',
            //   function () {
            //     const $btns = $('.bn-times button:not([data-type="btn"])')
            //     const $btn = $(this)
            //     const primaryStr = 'pear-btn-primary'
            //     const isSel = $btn.hasClass(primaryStr)
            //     let score = $btn.attr('data-score')
            //     let type = $btn.attr('data-type')
            //     currentTime = type
            //     $.each($btns, (index, btn) => $(btn).removeClass(primaryStr))
            //     $btn[isSel ? 'removeClass' : 'addClass'](primaryStr)
            //   }
            // )

            const renderAverageTimeTable = function () {
              layui.table.render({
                elem: '#average-timebox',
                height: 'full',
                data: data,
                skin: 'line',
                toolbar: false,
                cols: [
                  [
                    {
                      field: 'region_id',
                      title: '所属节点',
                      templet: function (d) {
                        let field = 'region_id'
                        if (typeof d[field] == 'undefined') return ''
                        let items = []
                        layui.each((d[field] + '').split(','), function (k, v) {
                          items.push(apiResults[field][v] || v)
                        })
                        return util.escape(items.join(','))
                      },
                    },
                    { field: 'ip', title: 'IP' },
                    { field: 'port', title: '端口', width: 100 },
                    { field: 'account', title: '用户名' },
                    { field: 'pass', title: '密码' },
                    { field: 'expire_time', title: '到期时间' },
                    {
                      field: 'status',
                      title: '状态',
                      templet: (d) => (d.status == 1 ? '已平均' : '待平均'),
                    },
                  ],
                ],
              })
            }

            layer.open({
              type: 1,
              title: '平均时间',
              shade: 0.1,
              maxmin: false,
              area: [common.isModile() ? '100%' : '60%', common.isModile() ? '100%' : '95%',],
              content: $('#average-time-wrapper'),
              btnAlign: 'c',
              btn: ['确认平均', '取消'],
              yes: function (index, layero) {
                // NOTE: 确认平均
                if (currentTime == '') return layer.msg('请选择平均时间')
                layer.load()
                APILIST.setAverageTime(
                  {
                    line_id: defaultLineId,
                    ids: data.map((item) => item.id),
                    date: currentTime,
                    user_id: defaultUserId, // UserId
                  },
                  (res) => {
                    layer.close(index)
                    layer.closeAll('loading')
                    layui.notice.info(res.msg)
                    window.refreshTable()
                  }
                )
              },
              btn2: function (index, layero) {
                layer.close(index)
              },
              success: function () {
                renderAverageTimeTable()
              },
            })
          }

          // 修改密码
          let __change_password__ = function (data) {
            if (!data || !data.length) return layui.popup.warning('未选中数据')
            $('#change-password-input').val('')
            let tableInstance = null

            const renderChangePasswordTable = function () {
              tableInstance = layui.table.render({
                elem: '#change-password',
                height: 'full',
                data: data,
                skin: 'line',
                toolbar: false,
                cols: [
                  [
                    {
                      field: 'region_id',
                      title: '所属节点',
                      templet: function (d) {
                        let field = 'region_id'
                        if (typeof d[field] == 'undefined') return ''
                        let items = []
                        layui.each((d[field] + '').split(','), function (k, v) {
                          items.push(apiResults[field][v] || v)
                        })
                        return util.escape(items.join(','))
                      },
                    },
                    { field: 'ip', title: 'IP' },
                    { field: 'account', title: '用户名' },
                    { field: 'pass', title: '密码' },
                    {
                      field: 'newpass',
                      title: '新密码',
                      templet: function (d) {
                        return `<input type="text" placeholder="请输入新密码" name="newpass" class="layui-input layui-input-sm" style="height: 100%" />`
                      },
                    },
                    {
                      field: 'status',
                      title: '状态',
                      templet: (d) => (d.status == 1 ? '已修改' : '待修改'),
                    },
                  ],
                ],
              })

              //   layui.table.on('edit(test)', function (obj) {
              //     //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
              //     console.log(obj.value) //得到修改后的值
              //     console.log(obj.field) //当前编辑的字段名
              //     console.log(obj.data) //所在行的所有相关数据
              //   })
            }

            layer.open({
              type: 1,
              title: '修改密码',
              shade: 0.1,
              maxmin: false,
              area: [common.isModile() ? '100%' : '60%', common.isModile() ? '100%' : '95%',],
              content: $('#change-password-wrapper'),
              btnAlign: 'c',
              btn: ['确认修改', '取消'],
              yes: function (index, layero) {
                // NOTE: 修改密码确认
                const globalPass = $('#change-password-input').val()
                const formData = {
                  // type 类型1=批量修改,2=列表修改
                  type: globalPass ? 1 : 2,
                  password: globalPass,
                  data: [],
                }
                const inputs = $(
                  '#change-password-wrapper input[name="newpass"]'
                )
                let pass = false
                $.each(data, function (index, item) {
                  formData.data.push({
                    id: item.id,
                    password: $(inputs[index]).val(),
                  })
                })
                for (let i = 0; i < formData.data.length; i++) {
                  const item = formData.data[i]
                  if (!item.password) {
                    pass = true
                    break
                  }
                }

                // 列表修改时；需要判断是否有密码
                if (formData.type == 2 && pass) {
                  layer.msg('密码尚未完善')
                  return
                }

                layer.load()
                APILIST.putUserUpdatePwd(
                  {
                    user_id: defaultUserId,
                    line_id: defaultLineId,
                    ...formData,
                  },
                  (res) => {
                    layer.closeAll()
                    layui.notice.info(res.msg)
                    window.refreshTable()
                  }
                )
              },
              btn2: function (index, layero) {
                layer.close(index)
              },
              success: function () {
                renderChangePasswordTable()
              },
            })
          }

          // 地区调换 x 3
          function executeAction({ id }, data) {
            if (!data || !data.length) return layui.popup.warning('未选中数据')

            // 多地区不可调换
            var a = data[0]['game_id'],
              i = !1
            data.forEach(function (e, n) {
              if (e['game_id'] != a && 0 == i)
                return (
                  layui.popup.warning('不能同时调换多个项目'),
                  void (i = !0)
                )
            })
            if (i) return

            // 1 数据过期不能选择
            const currentTimeStamp = Date.now()
            const hasExpired = data.some(
              (item) => new Date(item.expire_time).getTime() < currentTimeStamp
            )

            if (hasExpired) return layui.popup.warning('选择的数据已过期')

            // 游戏调换
            if(id == 4){
              exchangeGame(data);
              return;
            }

            // Reset dialog context.
            $('#change-same-area-wrapper #change-same-area-table').html('')
            $(
              '#change-same-area-wrapper div[lay-id="change-same-area-table"]'
            ).remove()
            $('#change-same-area-wrapper form .layui-form-item:eq(2)').hide()

            $(
              'form[lay-filter="change-same-area-form"] > div.layui-form-item:eq(1)'
            ).hide()

            $('div[lay-filter="change-same-area-tab"]')[
              id === 3 ? 'show' : 'hide'
            ]()

            const executeSomething = () => {
              switch (id) {
                case 1:
                  handleChangeSameArea(data, undefined, {
                    apiResults,
                  })
                  break
                case 2:
                  handleChangeSameArea(data, true, {
                    apiResults,
                  })
                  break
                case 3:
                  handleChangeAreaIP(data)
                  break
              }
            }

            if (!window.Accounts) {
              APILIST.getCustomAccountList((data = []) => {
                window.Accounts = data
                executeSomething()
              })
            } else executeSomething()
          }

          // 游戏调换
          let exchangeGame = function(data){
            const ids = data.map((item) => item.id)
            layer.open({
              type: 2,
              title: "游戏调换",
              shade: 0.1,
              maxmin: true,
              area: [common.isModile()?"100%":"60%", common.isModile()?"100%":"95%"],
              content: ORDERDETAIL_GAME_URL + "?" + 'line_id=' +defaultLineId+ '&ids' + "=" + ids,
              skin: ''
            });
          }

          // 自动续费开启/关闭
          let renewAutoOpen = function (data,status) {
            if (!data || !data.length){
              return layui.popup.warning('未选中数据')
            }
            const order_node_ids = data.map((item) => item.id)
            doRenewAutoOpen(order_node_ids,status)
          }

          // 执行自动续费开启/关闭
          let doRenewAutoOpen = function (ids,status) {
            let title = '';
            let content = '';
            if(status == 1){
              title = '开启自动续费';
              content = '<div id="" class=""><strong><font color="red">确定要开启自动续费？<br/>'+configText+'</font></strong></div>';
            } else{
              title = '关闭自动续费';
              content = '<div id="" class=""><strong><font color="red">确定要关闭自动续费？</font></strong></div>';
            }

            layer.open({
              // type: 1,
              title: title,
              shade: 0.1,
              maxmin: true,
              content: content,
              skin: '',
              btn: ['确定', '取消'],
              yes: function (index, layero) {
                $.ajax({
                  url: RENEW_AUTO_OPEN_API,
                  data: {ids: ids,status:status},
                  dataType: 'json',
                  type: 'post',
                  success: function (res) {
                    layer.close(index)
                    if (res.code) {
                      return layui.popup.failure(res.msg)
                    }
                    window.refreshTable()
                    return layui.popup.success(res.msg)
                  },
                  error: function () {
                    layer.close(index)
                    return layui.popup.failure('网络错误')
                  },
                })
              },
              btn2: function (index, layero) {
                layer.close(index)
              },
            });
          }

          // 解绑
          let bind = function (data) {
            if (!data || !data.length){
              return layui.popup.warning('未选中数据')
            }
            const ipIds = data.map((item) => item.id)
            doBind(ipIds)
          }

          // 执行解绑
          let doBind = function (ids) {
            layer.confirm('确定解绑?', {icon: 3, title: '解绑',}, function (index) {
                      layer.close(index)
                      let loading = layer.load()
                      $.ajax({
                        url: BIND_API,
                        data: {ids:ids},
                        dataType: 'json',
                        type: 'post',
                        success: function (res) {
                          layer.close(loading)
                          if (res.code) {
                            return layui.popup.failure(res.msg)
                          }
                          layui.notice.info(res.msg)
                          window.refreshTable()
                          return true;
                          // return layui.popup.success(res.msg)
                        },
                        error: function () {
                          layer.close(loading)
                          return layui.popup.failure('网络错误')
                        },
                      })
                    }
            )
          }

          /*-------按钮操作 end----------*/


          if(defaultUserId > 0){
            // 渲染选项卡
            let lineSelectData = <?=$line_list?>;
            layui.use(["jquery", "popup"], function() {
              let html = '';
              $.each(lineSelectData,function(index,value){
                if(value.id == defaultLineId){
                  html += "<li class='layui-this' lay-submit lay-filter='table-type' data-type='"+value.id+"'>" + value.name + "</li>";
                } else{
                  html += "<li lay-submit lay-filter='table-type' data-type='"+value.id+"'>" + value.name + "</li>";
                }
              })
              $("#typeData").html(html);
              $('#line_id').val(defaultLineId);
            });

            // 选项卡点击事件
            form.on("submit(table-type)", function(data) {
              let type = $(this).data('type');
              $('#line_id').val(type);
              defaultLineId = type // NOTE: 选项卡更换分区时 切换默认的展示分区、用于其他接口使用
              return false;
            });
          }
        }
      )
    </script>
  </body>
</html>
